package cn.snmp.mutual.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author dengkn
 * */

public class StackPrinter {
	
	private BufferedWriter bufferedWriter;

	public StackPrinter(String typeName) {
		this(typeName, (String) null);
	}

	public StackPrinter(String typeName, String dataFormat) {
		if (typeName == null || typeName.length() == 0) {
			typeName = "Default";
		}

		if (dataFormat == null || dataFormat.length() == 0) {
			dataFormat = "yyyyMMddHHmmss";
		}

		String name = "data_collect" + File.separator + typeName + (new SimpleDateFormat(dataFormat)).format(new Date())
				+ ".log";
		this.initIO(name);
	}

	private void initIO(String fileName) {
		File dir = new File("data_collect");
		if (!dir.exists()) {
			dir.mkdirs();
		}

		File file = new File(fileName);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException arg5) {
				return;
			}
		}

		try {
			this.bufferedWriter = new BufferedWriter(new FileWriter(file, true));
		} catch (IOException arg4) {
			this.close();
		}

	}

	public void close() {
		try {
			if (this.bufferedWriter != null) {
				this.bufferedWriter.close();
			}
		} catch (IOException arg1) {
			;
		}

	}

	public synchronized void print(String str) {
		if (this.bufferedWriter != null) {
			try {
				this.bufferedWriter.append("DataCollect: ");
				this.bufferedWriter.append((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
				this.bufferedWriter.newLine();
				this.bufferedWriter.append(str);
				this.bufferedWriter.newLine();
				StackTraceElement[] e = Thread.currentThread().getStackTrace();
				int i = 3;

				for (int length = e.length; i < length; ++i) {
					this.bufferedWriter.append(e[i].toString());
					this.bufferedWriter.newLine();
				}

				this.bufferedWriter.flush();
			} catch (IOException arg4) {
				;
			}

		}
	}
}